﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI;

namespace blackhouse.Web.Controls {
	public abstract class ActionControl {

		#region CONST

		internal string PAGE_ITEMS_COUNT_KEY = "action_counter";
		internal string CSS_CLASS_SIGN_PATTERN = "actionControl{0}";

		#endregion

		#region Fields

		protected WebControl visitControl;
		protected Dictionary<string,string> parameters;
		private string classNameId;

		#endregion

		#region Constructors

		public ActionControl(WebControl visitControl) {
			this.visitControl = visitControl;
			this.parameters = new Dictionary<string, string>();
		}

		#endregion

		#region Methods

		public ActionControl AddParameter(string key, object value) {
			if(this.parameters.ContainsKey(key))
				this.parameters[key] = value.ToString();
			else
				this.parameters.Add(key, value.ToString());
			return this;
		}

		private Page getCurrentPage() {
			if(HttpContext.Current != null && HttpContext.Current.Handler != null)
				return HttpContext.Current.Handler as Page;
			else return null;
		}

		protected string getId() {
			if(!string.IsNullOrEmpty(this.classNameId)) return classNameId;
			Page crnPage = this.getCurrentPage();
			if(crnPage != null) {
				int counter = 0;
				if(crnPage.Items.Contains(PAGE_ITEMS_COUNT_KEY))
					counter = Convert.ToInt32(crnPage.Items[PAGE_ITEMS_COUNT_KEY]);
				counter++;
				crnPage.Items[PAGE_ITEMS_COUNT_KEY] = counter;
				this.classNameId = string.Format(CSS_CLASS_SIGN_PATTERN, counter);
				return this.classNameId;
			} else return "";
		}

		public void Bind() {
			if(this.parameters.Count == 0) return;
			if(this.visitControl.CssClass.Length > 0)
				this.visitControl.CssClass += " ";
			this.visitControl.CssClass += this.getId();
			this.bind();
		}

		protected abstract void bind();

		#endregion

	}
}